昨日我們談到了content negotiation讓我們可以透過Accept Header Strategy/URL Parameter Strategy可以取得不一樣的數據類型,那麼它背後的原理是什麼呢?如果今天我還想要再加入其他的數據類型是否可以做得到呢?這就是今天我們要討論的
<!--加入對yaml的依賴-->
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-yaml</artifactId>
</dependency>
簡單的來說HttpMessageConverter就是作為Spring MVC與Request/Response中間橋梁,透過它做訊息的轉換讓他們可以互相溝通
自訂義的MyYamlHttpMessageConverter
public class MyYamlHttpMessageConverter extends AbstractHttpMessageConverter<Object> {
private ObjectMapper objectMapper = null; //把物件轉成yaml
public MyYamlHttpMessageConverter(){
super(new MediaType("text","yaml", Charset.forName("UTF-8")));
//告訴Spring Boot符合哪種類型
YAMLFactory factory = new YAMLFactory()
.disable(YAMLGenerator.Feature.WRITE_DOC_START_MARKER);
this.objectMapper = new ObjectMapper(factory);
}
@Override
protected boolean supports(Class<?> clazz) {
return true;
}
@Override //@RequestBody
protected Object readInternal(Class<?> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
return null;
}
@Override //@ResponseBody 把物件寫出去
protected void writeInternal(Object methodReturnValue, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
try(OutputStream os = outputMessage.getBody()){
this.objectMapper.writeValue(os,methodReturnValue);
}
}
}
配置類
@Configuration
public class MyHttpMessageConvertersConfiguration {
@Bean
public WebMvcConfigurer webMvcConfigurer(){
return new WebMvcConfigurer() {
@Override //配置一個能把對象轉為yaml的messageConverter
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.add(new MyYamlHttpMessageConverter());
}
};
}
}
Controller
@RestController
public class HelloController {
@GetMapping("/emp")
public Employee emp(){
return new Employee("james","2023100401","IT","A01");
}
}
Result